<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\City;
use common\services\system\CityService;

class CityController extends AuthController
{
    use CommonAction;

    protected string $model = City::class;
    protected bool $validate = true;


    protected function deleteBefore(City $model, string $type): string
    {
        $child = City::findOne(['parent_id' => $model->id]);
        if ($child) return '该地区有下级，无法删除';
        return '';
    }

    protected function infoAfter(City $model): array
    {

        $parentName = '';
        if ($model->parent_id > 0) {
            $parentInfo = City::findOne($model->parent_id);
            if ($parentInfo) $parentName = $parentInfo->name;
        } else {
            $parentName = '中国';
        }
        $info = $model->toArray();
        $info['parent_name'] =$parentName;

        return $this->success('', ['info' => $info]);
    }

    protected function saveBefore(City $model, string $type): string
    {
        if ($type == 'add' || $type == 'edit') {
            if ($model->parent_id) {
                $parent = City::findOne($model->parent_id);
                if (!$parent) return '上级地区不存在';
                $model->level = $parent->level + 1;
                $model->merge_name = $parent->short_name.'-'.$model->short_name;
            } else {
                $model->level = 0;
                $model->merge_name = $model->short_name;
            }
        }
        return '';
    }

    public function actionSelect(): array
    {
        return $this->success('', ['list'=>CityService::selectList()]);
    }
}
